package meijuli.com.join51.business.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.liaoinstan.springview.widget.SpringView;
import com.youngfeng.architecture.image.CircleTransform;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.adapter.CustomAdapter;
import meijuli.com.join51.business.adapter.CustomHolder;

import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.Order;
import meijuli.com.join51.business.orderdetail.OrderDetailActivity;
import meijuli.com.join51.business.orderdetail.OrderDetailFramge;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.ui.LoadFooterView;
import meijuli.com.join51.business.ui.RefreshHeaderView;
import meijuli.com.join51.business.ui.widget.CustomItemDecoration;
import com.jhx.common.utils.DisplayUtil;
import com.jhx.common.utils.ToastUtil;
import retrofit2.Call;

/**
 * 订单列表页
 *
 * @author jack 2017-05-02 10:35
 */
public class OrderListFragment extends BaseFragment {
    SpringView mRefreshLayout;
    RecyclerView mOrderRecyclerView;
    ViewStub mViewStub;
    private final static int PAGE_SIZE = 20;
    private CustomAdapter<Order> mOrderAdapter;
    private Call<HttpResponse<List<Order>>> mCall;
    public static final String KEY_DATA = "data";
    private List<Order> mOrderList;
    private int mPageIndex = 1;
    private boolean mIsLoading = false;
    private boolean mIsRefresh = true;
    public boolean mFirstLoad = true;
    private boolean mIsMore = true;
    private String requestOrderStatus;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_orderlist, container, false);
        mRefreshLayout = view.findViewById(R.id.refresh_layout);
        mOrderRecyclerView = view.findViewById(R.id.recyclerview_order);
        mViewStub = view.findViewById(R.id.viewstub_empty);
        mOrderList = new ArrayList<>();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mRefreshLayout.setHeader(new RefreshHeaderView(getActivity()));
        mRefreshLayout.setFooter(new LoadFooterView(getActivity()));
        mRefreshLayout.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                if (mIsLoading) {
                    return;
                }
                mIsLoading = true;
                mIsRefresh = true;
                mPageIndex = 1;
                loadData();
            }

            @Override
            public void onLoadmore() {
                if (mIsLoading) {
                    return;
                }
                if (!mIsMore) {
                    mRefreshLayout.onFinishFreshAndLoad();
                    ToastUtil.getInstance().showToast(getActivity(), "没有更多数据啦...");
                    return;
                }
                mIsRefresh = false;
                loadData();
            }
        });
        lazyLoad();
    }

    public static OrderListFragment newInstance(int status) {
        OrderListFragment fragment = new OrderListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(KEY_DATA, status);
        fragment.setArguments(bundle);
        return fragment;
    }
    void lazyLoad() {
        if (mFirstLoad) {
            showLoadingDialog();
            loadData();
            mFirstLoad = false;
        }
    }
    public void loadData() {
        int status = getArguments().getInt(KEY_DATA);
        requestOrderStatus = "" + status;
        if (status == Order.STATUS_ALL) {
            requestOrderStatus = null;
        }
        mCall = ApiManager.get().getApiService(ApiService.class).getOrders(requestOrderStatus, mPageIndex, PAGE_SIZE);
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<List<Order>>() {

            @Override
            public void onSuccess(String url, List<Order> data) {
                setAdapter(data);
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                mIsLoading = false;
                dismissDialog();
                mRefreshLayout.onFinishFreshAndLoad();
            }
        });
    }

    private void setAdapter(List<Order> list) {
        mIsLoading = false;
        mPageIndex++;
        mRefreshLayout.onFinishFreshAndLoad();
        dismissDialog();
        if (mIsRefresh) {
            mOrderList.clear();
        }

        if (list != null && list.size() > 0) {
            mViewStub.setVisibility(View.GONE);
            mOrderList.addAll(list);
            if (mOrderAdapter == null) {
                mOrderAdapter = createAdapter();
                mOrderRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                CustomItemDecoration decoration = new CustomItemDecoration(
                        DisplayUtil.dip2px(getActivity(), 1),
                        LinearLayoutManager.HORIZONTAL);
                mOrderRecyclerView.addItemDecoration(decoration);
                mOrderRecyclerView.setAdapter(mOrderAdapter);
                mOrderAdapter.setOnItemClickListener(new CustomAdapter.OnItemClickListener() {
                    @Override
                    public void onClick(View view, int position) {
                        Intent intent = new Intent(getActivity(), OrderDetailActivity.class);
                        intent.putExtra(OrderDetailFramge.Companion.getKEY_ORDER(), mOrderList.get(position));
                        startActivity(intent);
                    }
                });
            } else {
                mOrderAdapter.updateView(mOrderList);
            }
        } else {
            if (mIsRefresh) {
                mViewStub.setVisibility(View.VISIBLE);
            } else {
                mIsMore = false;
            }
        }
    }

    private CustomAdapter<Order> createAdapter() {
        return new CustomAdapter<Order>(mOrderList, getActivity(), R.layout.item_order, null) {
            @Override
            public void onBindData(CustomHolder holder, int position, final Order order) {
                TextView statusTxt   = holder.findView(R.id.text_status);
                TextView orderNumTxt = holder.findView(R.id.text_ordernum);
                ImageView userImg    = holder.findView(R.id.img_user);
                TextView tipsTxt     = holder.findView(R.id.txt_tips);
                TextView timeTxt     = holder.findView(R.id.txt_time);
                TextView priceTxt    = holder.findView(R.id.txt_price);
                int mOrderStatus = order.getOrderStatus();
                if (mOrderStatus == Order.STATUS_WAIT_PAYMENT) {
                    statusTxt.setText("未收款");
                } else if (mOrderStatus == Order.STATUS_SUCCESS) {
                    statusTxt.setText("已收款");
                }
                orderNumTxt.setText("订单号：" + order.getDmId());
                Glide.with(getActivity())
                        .load(order.getUserHeadUrl())
                        .transform(new CircleTransform(getActivity()))
                        .error(R.mipmap.icon_header)
                        .into(userImg);
                if(!TextUtils.isEmpty(order.getUserNick())) {
                    tipsTxt.setVisibility(View.VISIBLE);
                    tipsTxt.setText(order.getUserNick() + "-付款");
                } else {
                    tipsTxt.setVisibility(View.GONE);
                }

                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Date date = new Date(order.getCrtime());
                String time = dateFormat.format(date);
                timeTxt.setText(time);
                priceTxt.setText("￥ " + order.getActPrice());
            }
        };
    }
}
